package cn.fl.ref.fncprjpaysch.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjpaysch.service.IFncPrjPayInsService;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPayInsVO;
import cn.fl.system.constant.SysLogConstant;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import fl.ref.fncprjpaysch.condition.FncPrjPayInsQueryCondition;
import fl.ref.fncprjpaysch.constant.FncPrjPaySchConstant;
import fl.ref.fncprjpaysch.service.IFncPrjPayInsApiService;

/**
 * @Description: 再融资支付表机构关系控制层
 */
@Controller
@RequestMapping("/rfbase/fncPrjPayIns")
public class FncPrjPayInsController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FncPrjPayInsController.class);

	/**
	 * FncPrjPayIns 服务层BEAN
	 */
	@Autowired
	private IFncPrjPayInsService fncPrjPayInsService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IFncPrjPayInsApiService fncPrjPayInsApiService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/fncPrjPayIns/fncPrjPayInsList");
		String sysCd=CurrentThreadContext.getCurrentSysCd();
		String orgCd=CurrentThreadContext.getCurrentOrgCd();
		view.addObject("stCdLst", sysDictionaryApiService.getKvList(FncPrjPaySchConstant.FNC_PRJ_PAY_INS_ST_CD, sysCd, orgCd));
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("rfbase/fncPrjPayIns/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(FncPrjPayInsQueryCondition qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		//FncPrjPayInsQueryCondition qc = new FncPrjPayInsQueryCondition();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.fncPrjPayInsService.searchListPage(page);
		List<FncPrjPayInsVO> list = (List<FncPrjPayInsVO>) pager.getResultList();
		ListPageVO<FncPrjPayInsVO> listPage = new ListPageVO<FncPrjPayInsVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.fncPrjPayInsService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FncPrjPayInsVO vo = this.fncPrjPayInsService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public Object add(FncPrjPayInsVO entity ,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		
		try {
			//entity = new FncPrjPayInsVO();
			//TODO ADD PARAM
			Long id = this.fncPrjPayInsService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FncPrjPayInsVO entity = null;
		try {
			entity = new FncPrjPayInsVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.fncPrjPayInsService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	@RequestMapping(value = "/exportExcel.do", method = {RequestMethod.GET , RequestMethod.POST })
	@ResponseBody
	public Object exportExcel(FncPrjPayInsQueryCondition qc,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String currentPage = "1";
		String pageSize = "999999";
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,
				"导出成功");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.fncPrjPayInsService.searchListPage(page);
		List<FncPrjPayInsVO> list = (List<FncPrjPayInsVO>) pager.getResultList();
		
		try {
			// JSONArray jsonArray = JSON.parseArray(jsonArrayData);
			List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
			String filename="pay.xlsx";
			
			ExportParams params = new ExportParams(null, null,ExcelType.XSSF);
			params.setTitleHeight((short) 5);
	        params.setColor(HSSFColor.LIGHT_TURQUOISE.index2);//表头颜色
	        params.setHeaderColor(HSSFColor.WHITE.index);//间隔颜色-未启用
			Workbook wb = ExcelExportUtil.exportExcel(params,FncPrjPayInsVO.class,list);
			response.setHeader("Content-disposition", filename);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename="
					+ filename);
			response.setHeader("Pragma", "No-cache");
			OutputStream ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
//			FncPrjBscInfoController c = new FncPrjBscInfoController();
//			c.export("资产包表-" , "资产", excelHeader, ds_titles, ds_format,
//					null, data, request, response);
		} catch (Exception e) {
			logger.error("导出文件异常", e);
		}
		return result;
	} 
	/**
	 * 分账支付表发送租金短信每天8点开始
	 */
	@RequestMapping(value = "/sendSmsByFenPay.do", method = { RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public Object sendSmsByFenPay(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		
		try {
			//entity = new FncPrjPayInsVO();
			//TODO ADD PARAM
			this.fncPrjPayInsApiService.sendSmsByFenPay();
			
			BaseLogUtils.info(logger, "add", "分账支付表发送租金短信每天8点开始.[] DATA:" , CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "分账支付表发送租金短信每天8点开始失败.DATA:"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "分账支付表发送租金短信每天8点开始失败.DATA:"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
}

